package com.wugui.datax.admin.config;

import cn.hutool.core.util.ObjectUtil;
import com.wugui.datax.admin.entity.JobUser;
import com.wugui.datax.admin.service.UserService;
import com.wugui.datax.admin.service.impl.UserDetailsServiceImpl;
import com.wugui.datax.admin.service.impl.UserServiceImpl;
import org.datanucleus.store.rdbms.identifier.IdentifierFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.filter.EqualsFilter;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
@Component
public class LdapAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    @Qualifier(value = "ldapTemplate")
    private LdapTemplate ldapTemplate;
    @Autowired
    private UserService userService;
    @Value("${datax.default.roles}")
    private String ROLES;
    @Qualifier(value = "customUserService")
    @Autowired
    private UserDetailsService userDetailsService;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();
        boolean flag=false;
        try {
            EqualsFilter filter = new EqualsFilter("uid", username);
            flag=ldapTemplate.authenticate("", filter.toString(), password);
            //登录ldap认证，如果认证不通过，则禁止登录，给出错误提示，
            // 如果ldap认证通过，判断本地数据库是否有用户，如果没有则新增用户数据，默认角色ROLE_ADMIN
            UserDetails userDetails=userDetailsService.loadUserByUsername(username);
            if(flag && ObjectUtil.isNull(userDetails)){
                    JobUser jobUser=new JobUser()
                            .setUsername(username)
                            .setPassword(password)
                            .setRole(ROLES);
                    userService.saveUser(jobUser);
            }
        } catch (Exception e) {
            throw new BadCredentialsException("Invalid LDAP username or password");
        }
        if (!flag) {
            throw new BadCredentialsException("Invalid LDAP username or password");
        }
        return new UsernamePasswordAuthenticationToken(username, password, authentication.getAuthorities());
    }
    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
